#-*- coding:UTF-8 -*-


import cStringIO
import re

from ..logger import logger
from ..config import PLATMGT_HOME, get_property
from ..orm.models import *
from ..orm.db_util import get_objects, count_object


URL_BASE = '/%s/%s/pages/'%(get_property('url.prefix', '').rstrip('/'), get_property('app.prefix', '').rstrip('/'))


SIDEBAR_MENU_HTML_STRING = '''
      <!-- sidebar menu of zhaoxp starts -->
      <ul class="sidebar-menu">
        <li class="header">MAIN NAVIGATION</li>
        <li class="{m0} treeview">
          <a href="{URL_BASE}index.html">
            <i class="fa fa-dashboard"></i> <span>Dashboard</span>
          </a>
        </li>
        <!-- usergroup(user|group) -->
        <li class="{m1} treeview">
          <a href="#">
            <i class="fa fa-user-plus"></i>
            <span>User&Group</span>
            <span class="pull-right-container">
              <i class="fa fa-angle-left pull-right"></i>
            </span>
          </a>
          <ul class="treeview-menu">
            <li class="{m11}"><a href="{URL_BASE}users.html"><i class="fa fa-user"></i> User</a></li>
            <li class="{m12}"><a href="{URL_BASE}groups.html"><i class="fa fa-users"></i> Group</a></li>
          </ul>
        </li>
        <!-- resource(System|host) -->
        <li class="{m2} treeview">
          <a href="#">
            <i class="fa fa-sitemap"></i>
            <span>Resource</span>
            <span class="pull-right-container">
              <i class="fa fa-angle-left pull-right"></i>
            </span>
          </a>
          <ul class="treeview-menu">
            <li class="{m21}"><a href="{URL_BASE}datacenters.html"><i class="fa fa-clone"></i> DataCenter</a></li>
            <li class="{m22}"><a href="{URL_BASE}systems.html"><i class="fa fa-clone"></i> System</a></li>
            <li class="{m23}"><a href="{URL_BASE}hosts.html"><i class="fa fa-server"></i> Host</a></li>

          </ul>
        </li>
      </ul>
      <!-- sidebar menu of zhaoxp  ends  -->
'''.replace('{URL_BASE}', URL_BASE)


def render_sidebar_menu(tag_list=[]):
    logger.debug('start to render sidebar menu')
    it = re.finditer('\{m\d+\}', SIDEBAR_MENU_HTML_STRING, re.M)
    render_dict = {}
    for match in it:
        render_dict[match.group()[1:-1]] = ''
    #for k, v in render_dict.items():
    #    print k, '=', v
    for tag in tag_list:
        if tag in render_dict.keys():
            render_dict[tag] = 'active'
    return SIDEBAR_MENU_HTML_STRING.format(**render_dict)


DEFAULT_SIDEBAR_MENU_DICT = dict({'sidebar_menu_content':render_sidebar_menu()})


class HtmlRequestHandler(object):
    '''
    all static methods return dict which contains at least {'sidebar_menu_content':xxx}
    '''

    @staticmethod
    def html_default(handler):
        #return DEFAULT_SIDEBAR_MENU_DICT
        return dict({'sidebar_menu_content':render_sidebar_menu(['m0'])})

    @staticmethod
    def html_404(handler):
        #return DEFAULT_SIDEBAR_MENU_DICT
        return dict({'sidebar_menu_content':render_sidebar_menu()})

    @staticmethod
    def html_index(handler):
        user_count   = count_object(User)
        group_count  = count_object(Group)
        system_count = count_object(System)
        host_count   = count_object(Host)
        #render_dict = DEFAULT_SIDEBAR_MENU_DICT.copy()
        render_dict = dict({'sidebar_menu_content':render_sidebar_menu(['m0'])})
        render_dict['user_count'] = user_count
        render_dict['group_count'] = group_count
        render_dict['system_count'] = system_count
        render_dict['host_count'] = host_count
        return render_dict

    @staticmethod
    def html_users(handler):
        user_list = get_objects(User)
        render_dict = dict({'sidebar_menu_content':render_sidebar_menu(['m1','m11'])})
        render_dict['user_list'] = user_list
        return render_dict
    
    @staticmethod
    def html_groups(handler):
        group_list = get_objects(Group)
        render_dict = dict({'sidebar_menu_content':render_sidebar_menu(['m1','m12'])})
        render_dict['group_list'] = group_list
        return render_dict
    
    @staticmethod
    def html_datacenters(handler):
        datacenter_list = get_objects(DataCenter)
        render_dict = dict({'sidebar_menu_content':render_sidebar_menu(['m2','m21'])})
        render_dict['datacenter_list'] = datacenter_list
        return render_dict
    
    @staticmethod
    def html_systems(handler):
        system_list = get_objects(System, attr_list=['creator'])
        render_dict = dict({'sidebar_menu_content':render_sidebar_menu(['m2','m22'])})
        render_dict['system_list'] = system_list
        return render_dict
    
    @staticmethod
    def html_hosts(handler):
        host_list = get_objects(Host, attr_list=['datacenter', 'creator'])
        render_dict = dict({'sidebar_menu_content':render_sidebar_menu(['m2','m23'])})
        render_dict['host_list'] = host_list
        return render_dict
    
    @staticmethod
    def html_test(handler):
        render_dict = dict({'sidebar_menu_content':render_sidebar_menu()})
        return render_dict



'''
class MenuItem(object):

    def __init__(self, name, top_menu=False, href='#', css_icon='', active=False, sub_menu_items=[]):
        self.name = name
        self.top_menu = top_menu
        self.href = href
        self.css_icon = css_icon
        self.active = active
        self.sub_menu_items = sub_menu_items

    def get_html(self, prefix_tab='', tab=' ', tab_size=2):
        html = cStringIO.StringIO()
        if self.sub_menu_items:
            deep = 1
            if self.top_menu:
                html.write(prefix_tab + tab * tab_size     + '<li class="treeview">\n')
            else:
                html.write(prefix_tab + tab * tab_size     + '<li>\n')
            html.write(prefix_tab + tab * tab_size * 2 + '<a href="#"><i class="fa ' + self.css_icon + '"></i>' + self.name + '\n')
            html.write(prefix_tab + tab * tab_size * 3 + '<span class="pull-right-container">\n')
            html.write(prefix_tab + tab * tab_size * 4 + '<i class="fa fa-angle-left pull-right"></i>\n')
            html.write(prefix_tab + tab * tab_size * 3 + '</span>\n')
            html.write(prefix_tab + tab * tab_size * 2 + '</a>\n')
            html.write(prefix_tab + tab * tab_size * 2 + '<ul class="treeview-menu">\n')
            for item in self.sub_menu_items:
                html.write(item.get_html(prefix_tab=prefix_tab+tab*tab_size*3, tab=tab, tab_size=tab_size))
            html.write(prefix_tab + tab * tab_size * 2 + '</ul>\n')
            html.write(prefix_tab + tab * tab_size     + '</li>\n')
        else:
            html.write(prefix_tab + '<li><a href="' + self.href + '"><i class="fa ' + self.css_icon + '"></i> ' + self.name + '</a></li>\n')
        return html.getvalue()


def init_menu():
    menu_usergroup = MenuItem('User&Group',top_menu=True, css_icon='fa-user-plus')
    menu_item_user = MenuItem('User', href='users.html', css_icon='fa-user')
    menu_item_group = MenuItem('Group', href='groups.html', css_icon='fa-users')
    menu_usergroup.sub_menu_items = [menu_item_user, menu_item_group]
    menu_resource  = MenuItem('Resource', top_menu=True,  css_icon='fa-sitemap')
    menu_item_dc = MenuItem('DataCenter', href='datacenters.html', css_icon='fa-building')
    menu_item_system = MenuItem('System', href='systems.html', css_icon='fa-clone')
    menu_item_host = MenuItem('System', href='hosts.html', css_icon='fa-server')
    menu_resource.sub_menu_items = [menu_item_dc, menu_item_system, menu_item_host]
    return [menu_usergroup, menu_resource]

'''